package servlet;

import bean.Admin;
import dao.impl.AdminDaoImpl;
import util.PasswordUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//请求编码
        resp.setContentType("text/html;charset=utf-8");//响应编码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String Repassword = req.getParameter("Repassword");
        HttpSession session = req.getSession();
        if(PasswordUtils.checkPassword(password, Repassword)){
            Random random = new Random();
            int randomNumber = 1000 + random.nextInt(9000); // 生成uid
            String formattedNumber = String.format("%04d", randomNumber);
            System.out.println("uid:"+formattedNumber);
            Admin admin = new Admin();
            admin.setUid(formattedNumber);
            admin.setUsername(username);
            admin.setPassword(password);
            AdminDaoImpl adminDao = new AdminDaoImpl();
            int row = adminDao.addAdmin(admin);
            if (row > 0){
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }else{
                session.setAttribute("msg","系统出现错误，请重新尝试！"); //存储到缓存
                resp.sendRedirect("/err/error.jsp");
            }
        }else{
            System.out.println(Repassword+":"+password);
            session.setAttribute("msg","密码不一致！"); //存储到缓存
            resp.sendRedirect("/err/error.jsp");
        }
    }
}
